import axios from 'axios'
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    inputVal: '',
    flag: 'all'
  },
  mutations: {
    setList(state, list) {
      state.list = list
    },
    setInputVal(state, inputVal) {
      state.inputVal = inputVal
    },
    addList(state) {
      let obj = {
        "id": Math.random(),
        "info": state.inputVal,
        "done": false
      }

      state.list.push(obj)
      state.inputVal = ''
    },
    delList(state, id) {
      let index = state.list.findIndex(item => item.id === id)

      state.list.splice(index, 1)
    },
    changeFn(state, obj) {
      let index = state.list.findIndex(item => item.id === obj.id)

      state.list[index].done = obj.done
    },
    clearDone(state) {
      state.list = state.list.filter(item => item.done === false)
    },
    changeHight(state, flag) {
      state.flag = flag
    }
  },
  actions: {
    async setList(context) {
      const {data} = await axios.get('./listdata.json')
      
      context.commit('setList', data)
    }
  },
  getters: {
    noDone(state) {
      return state.list.filter(item => !item.done).length
    },
    infoList(state) {
      if(state.flag === 'all') {
        return state.list
      } else if(state.flag === 'nodone'){
        return state.list.filter(item => item.done === false)
      } else if(state.flag === 'done'){
        return state.list.filter(item => item.done === true)
      }
    }
  }
})
